package com.feilo.util;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	
	private static SessionFactory sessionFactory ;
	
	static{
		Configuration cf = new Configuration();
		sessionFactory = cf.configure().buildSessionFactory();
	}
	
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static Session getSession(){
		return sessionFactory.openSession();
	}

	public static void add(Object entity){
		Session session = null ;
		Transaction tx = null ;
		try {
			session = HibernateUtil.getSession();
			tx=session.beginTransaction();
			session.save(entity);
			tx.commit();			
		} finally{
			if(session!=null){
				session.close();
			}
		}
	}
	
	public static void update(Object entity){
		Session session = null ;
		Transaction tx = null ;
		try {
			session = HibernateUtil.getSession();
			tx=session.beginTransaction();
			session.update(entity);
			tx.commit();			
		} finally{
			if(session!=null){
				session.close();
			}
		}
	}
	
	public static void del(Object entity){
		Session session = null ;
		Transaction tx = null ;
		try {
			session = HibernateUtil.getSession();
			tx=session.beginTransaction();
			session.delete(entity);
			tx.commit();			
		} finally{
			if(session!=null){
				session.close();
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T get(Class<T> clazz,Serializable id){
		Session session = null ;
		try {
			session = HibernateUtil.getSession();
			T entity = (T)session.get(clazz, id);
			return entity ;
		} finally{
			if(session!=null){
				session.close();
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T get(Class<T> clazz,Serializable id,boolean lazyFlag){
		Session session = null ;
		try {
			session = HibernateUtil.getSession();
			return (T)session.get(clazz, id);
		} finally{
			if(session!=null){
				session.close();
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T load(Class<T> clazz,Serializable id){
		Session session = null ;
		try {
			session = HibernateUtil.getSession();
			T entity = (T)session.load(clazz, id);
			//System.out.println(((User)entity).getName());
			//Hibernate.initialize(entity);
			return entity ;
		} finally{
			if(session!=null){
				session.close();
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public static Object findBySQL(String hql){
		List<Object> obj=null;
		try {
			Query query= HibernateUtil.getSession().createQuery(hql);//������ѯ����
			obj=query.list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
}
